package com.cema.manage.common.utils.encryption;


import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.SecureRandom;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

public class RSAEncrypt {
    //////////测试秘钥对//////////////////
    //static final String privateKey = "MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAK7lnqKRA6vxFgco0hCeTD/ddppIvFxDzAA44ZZjDYWcnVXVmmLA/5ONdKt77lI3siybaaI3jXeP13hQ6tTP74IO1ZV1taTF7N4yHs2xm0rwMDGG0yMjrsVxOH9v1tdaAdtXM8NadUNbdiXlMmGgpI4/H8R94qgj2+H6E4ueCYyPAgMBAAECgYEAhE1e+0sHpAHzz+apQbj9pTI6jeuH0aPXpjNhMworKG+Y9V1oNFwa+dt/7lkJp1hKiEPoXLX5ZgCB1pofimzhmBS09FOTkoxocqwxgzsjV3Wx1mjzlJcWanjGTHzr8bk2KRNkXGCpl5pIORjakv1TYuDZHOOQTfiA3SJBn8YiW8ECQQD4RkqV+K6wZCO+OxRHfB6wpaLvZAcCSlbZ0WBTKuKq7FQDIcY+m/nzRSHwXLOTKuiqGIjWLchg6IcAwMCGc8Y7AkEAtFbQ4cNKmujct151zo30JLlhttHQGw5qdu3OqgiKCQ79Yp/un83sz4JrrlcgZmy3MyS9grT9dZ+sQaoHvKZpvQJBANWFRmIihMJo7SCOmMs94PsVCMMPaMO8gWNFIa2FJXnQVBR5eJCh/l4M57pbT4lTDtQy04Q3zawibvDj1PANI78CQGVosFtTyz8jFQKUPqDhWFnSWS1J/MFKMPohreYVmTGQ2VG9Z507WiAyUcUev1x5Y+eBkIPQrPqYyG/AYktmNO0CQQDh6GV6C2skvBe/AVFt+X/t6jbtnvRd7+OODafer3ozQcGBL8we4hfJeGGnEpXMNjXCF2jFe9qOq7/3lXRanft0";
    //public static final String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCu5Z6ikQOr8RYHKNIQnkw/3XaaSLxcQ8wAOOGWYw2FnJ1V1ZpiwP+TjXSre+5SN7Ism2miN413j9d4UOrUz++CDtWVdbWkxezeMh7NsZtK8DAxhtMjI67FcTh/b9bXWgHbVzPDWnVDW3Yl5TJhoKSOPx/EfeKoI9vh+hOLngmMjwIDAQAB";
    //////////end//////////////////

    //////////生产//////////////////
    static final String privateKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJEG6TdkA+b9Q/ABjCYBQM2k5oIc0Z4ScqGsmOnZwm5DIORzlC82i3HxskrYH1w7dCsnpeMasIsJldFilfPeTe95GfTf3zcyddtLw8clmFeByjUyzhVbCB/gwXY/xDvx3IFDqXUAsCyJVaIus2FNcBCCiiJ16O7vejcmeg6xOibpAgMBAAECgYBrLOBMvuzjV2dNhtc7ftGVJ7fxj7qZRqjQMe0PZI37TkCQk5l/CqAipKtOBEmor4c6HSLKon61QXAmPOT0Q+TzY2/Dsx5CHUU7TjzZDz6MUZlzIV0XLSG5RrSUP5+tgcIhRguGkYDN72unG/EJaz8Pf13uSs4t8hyQo2wAvHVLwQJBAORoi3+eg7Ms8hAHKfk10aPkkNaaSAMkc4TZ0SGr8qRRbaMGO5KqpYVHUHDf8yt7qcsZgCTUHYSnJE10aYQE9h8CQQCii9LoJl8eKDiLMQgCOko+HBTeW5cpwB58pUhR1REOCA7uzJkYu941ZTmZKcAEpdyIr2YjxO+GAE4iBo20k3H3AkA39UT35yXs574GHzsxSvYpaP3zFak+29dRXOvXjADOMQTjQ8ukixoyJN6YSMWSiaF3mK/EVhNFRI2oTDTtmymRAkB7a7Pu9gPPQDb+6XHtTxlEY8ostFrpJql/d3icOi5C+zdrdwrgTvYAkSXU+HCGlvIHDzd8/XHpy52IFHXQoQwtAkEAm5zIexKN0Mp3n/9VgAjgvTYRm+P8AysE2JqlQnElFgOlU8v+8vwjqHecbA5SYyl1wy07T5zN8uPgdBpKRjToBw==";
    public static final String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCRBuk3ZAPm/UPwAYwmAUDNpOaCHNGeEnKhrJjp2cJuQyDkc5QvNotx8bJK2B9cO3QrJ6XjGrCLCZXRYpXz3k3veRn03983MnXbS8PHJZhXgco1Ms4VWwgf4MF2P8Q78dyBQ6l1ALAsiVWiLrNhTXAQgooideju73o3JnoOsTom6QIDAQAB";
    private static final Logger logger = Logger.getLogger("RSAEncrypt");

    public static void main(String[] args) throws Exception {
        String s = "haha12355";
        Map<Integer, String> map = RSAEncrypt.genKeyPair();
        System.out.println("publicKey:" + map.get(0));
        System.out.println("privateKey:" +map.get(1) );
        String s2 = RSAEncrypt.encrypt(s, publicKey);
        System.out.println("公钥加密后：" + s2);
        System.out.println("私钥解密后：" + RSAEncrypt.decrypt(s2));
    }

    /**
     * 随机生成密钥对
     */
    public static Map<Integer, String> genKeyPair() {
        Map<Integer, String> keyMap = new HashMap<Integer, String>();  //用于封装随机产生的公钥与私钥
        try {
            // KeyPairGenerator类用于生成公钥和私钥对，基于RSA算法生成对象
            KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");

            // 初始化密钥对生成器，密钥大小为96-1024位
            keyPairGen.initialize(1024, new SecureRandom());

            // 生成一个密钥对，保存在keyPair中
            KeyPair keyPair = keyPairGen.generateKeyPair();
            RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();   // 得到私钥
            RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();  // 得到公钥

            // 得到公钥字符串
            String publicKeyString = new String(Base64.encodeBase64(publicKey.getEncoded()));
            // 得到私钥字符串
            String privateKeyString = new String(Base64.encodeBase64((privateKey.getEncoded())));

            // 将公钥和私钥保存到Map
            keyMap.put(0, publicKeyString);  //0表示公钥
            keyMap.put(1, privateKeyString);  //1表示私钥
        } catch (Exception e) {
            logger.info("生成公钥私钥异常：" + e.getMessage());
            return null;
        }
        return keyMap;
    }

    /**
     * RSA公钥加密
     *
     * @param str       需要加密的字符串
     * @param publicKey 公钥
     * @return 公钥加密后的内容
     */
    public static String encrypt(String str, String publicKey) {
        String outStr = null;
        try {
            //base64编码的公钥
            byte[] decoded = Base64.decodeBase64(publicKey.getBytes());
            RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
            //RSA加密
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, pubKey);
            outStr = Base64.encodeBase64String(cipher.doFinal(str.getBytes("UTF-8")));
        } catch (Exception e) {
            logger.info("使用公钥加密【" + str + "】异常：" + e.getMessage());
        }
        return outStr;
    }

    /**
     * RSA私钥解密
     *
     * @param str 加密字符串
     * @return 私钥解密后的内容
     */
    public static String decrypt(String str) {
        String outStr = null;
        try {
            //64位解码加密后的字符串
            byte[] inputByte = Base64.decodeBase64(str.getBytes("UTF-8"));
            //base64编码的私钥
            byte[] decoded = Base64.decodeBase64(privateKey);
            RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
            //RSA解密
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, priKey);
            outStr = new String(cipher.doFinal(inputByte));
        } catch (Exception e) {
            logger.info("使用私钥解密异常：" + e.getMessage());
            return "";
        }
        return outStr;
    }
}
